<template>
  <div>
    <router-view>
      <!-- <div></div>6 -->
      <div class="box">
        <el-card class="box-card">
          <template #header>
            <div style="font-size: 20px; font-weight: 600">
              <span>标签管理</span>
            </div>
            <div style="height: 2vh"></div>
            <div class="header">
              <div class="left">
                <el-input style="width: 150px; margin-right: 20px" v-model="Labelvalue" @input="searchDepart" placeholder="输入标签名称" />
                <el-date-picker style="margin-right: 20px" v-model="value" type="daterange" @change="searchDepart" range-separator="至"
                  start-placeholder="开始时间" end-placeholder="结束时间" size="default" />
                <!-- <el-button type="primary" @click="searchDepart()">搜索</el-button> -->
              </div>
              <div class="right">
                <el-button type="danger" @click="deleteBatches">批量删除</el-button>
                <el-button type="primary" @click="addOffice">新增标签</el-button>
              </div>
            </div>
          </template>
          <el-table v-loading="loading" ref="table" :data="pageData" style="width: 100%; margin-bottom: 20px" row-key="id"
            stripe="true" :cell-style="{ textAlign: 'center' }" :header-cell-style="{ 'text-align': 'center' }"
            max-height="68vh">
            <el-table-column type="selection" width="55" fixed="left" align="center" />
            <el-table-column prop="name" label="标签名称" width="180" fixed="left" align="center" />
            <el-table-column prop="back" label="背景颜色" width="250" align="center">
              <template #default="scope">
                <el-tooltip class="box-item" effect="dark" :content="scope.row.back" placement="top">
                  <div style="display: flex;justify-content: center;">
                    <div :style="{ backgroundColor: scope.row.back }" class="backeds" @click="copyColor(scope.row.back)">
                    </div>
                  </div>
                </el-tooltip>

              </template>
            </el-table-column>
            <el-table-column prop="admin_name" label="添加人" align="center" />
            <el-table-column prop="color" label="字体颜色" width="250" align="center">
              <template #default="scope">
                <el-tooltip class="box-item" effect="dark" :content="scope.row.color" placement="top">
                  <div style="display: flex;justify-content: center;">
                    <div :style="{ backgroundColor: scope.row.color }" class="backeds"
                      @click="copyColor(scope.row.color)"></div>
                  </div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="是否启用" width="180" align="center">
              <template #default="scope">
                <el-switch :value="scope.row.status === 1" @click="affirmSwitch(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column prop="create_time" label="创建时间" width="150" align="center" />
            <el-table-column label="操作" width="150" fixed="right" align="center">
              <!-- <template #default="scope">
              <img
                style="width: 20px; height: 20px; margin-right: 10px"
                src="../../assets/编辑.png"
                alt=""
                @click="handleEdit(scope.$index, scope.row)"
              />
              <img
                style="width: 20px; height: 20px"
                src="../../assets/删除-01.png"
                alt=""
                @click="handleDelete(scope.$index, scope.row)"
              />
            </template> -->
              <template #default="scope">
                <div style="display: flex; align-items: center; justify-content: center">
                  <el-button type="primary" plain size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                  <el-button type="danger" plain size="small"
                    @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div style="display: flex;justify-content: center;">
            <el-pagination style="padding: 10px" v-model:current-page="currentPage" v-model:page-size="pageSize"
              :page-sizes="[5, 10, 20, 30]" layout="total, sizes,->, prev, pager, next, jumper" :total="listNum"
              @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
        </el-card>
      </div>
      <!-- 新增/编辑页面 -->
      <el-dialog v-model="dialogFormVisible" :title="form.id <= 0 ? '新增标签信息' : '编辑标签信息'" @close="cancel()" width="40%">
        <div class="window">
          <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="标签名称" prop="name">
              <el-input style="width: 300px" v-model="form.name" placeholder="输入标签名称" />
            </el-form-item>
            <el-form-item label="字体颜色" prop="color">
              <el-color-picker v-model="form.color" />
            </el-form-item>
            <el-form-item label="背景颜色" prop="back">
              <el-color-picker v-model="form.back" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-switch v-model="form.status" />
            </el-form-item>
            <div style="direction: rtl;">
              <el-form-item>
                <el-button type="primary" @click="affirm(ruleFormRef)" v-if="form.id <= 0">新增</el-button>
                <el-button type="primary" @click="affirm(ruleFormRef)" v-else>保存</el-button>
                <div style="width: 10px;"> </div>
                <el-button @click="cancel(ruleFormRef)">取消</el-button>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </el-dialog>
    </router-view>
  </div>
</template>

<script setup>
import { ref, watchEffect, onMounted, reactive } from 'vue';
import { addLabel, Label, deleteLabel } from '../../api/lable';
const form = reactive({
  name: '', //标签名称
  back: '', //背景颜色
  color: '', //字体颜色
  status: true, //状态
  id: '',
  admin_id: JSON.parse(localStorage.getItem('data')).data.id,
});
// UEditor配置
const editorConfig = reactive({
  autoHeightEnabled: false,
  initialFrameHeight: 200,
  initialFrameWidth: '100%',
  UEDITOR_HOME_URL: '/ueditor/', // 访问 UEditor 静态资源的根路径publc里面的名称
  serverUrl: '/pc/pc/Fileimg/uderto', // 服务端接⼝
  uploadUrl: '/pc/pc/Fileimg/uderto' + '/kjyl-server-doctor/doctor/file/uploadFile',
  // enableAutoSave: true, // 开启从草稿箱恢复功能需要⼿动设置固定的 editorId，否则组件会默认随机⼀个，如果页⾯刷新，下次渲染的时候 editorId 会重新随机，
});
const dialogFormVisible = ref(false); //弹窗状态
const url = ref('https://lxt.jingyi.icu/'); //域名头
const listNum = ref(0); //列表总数
const currentPage = ref(1); //当前页码数
const pageSize = ref(10); //当前每页显示数量
const loading = ref(true); //加载状态
const ruleFormRef = ref(); //页面表单实例
const table = ref(); //表格实例
const LabelList = ref([]); //标签列表
const departvalue = ref(''); //搜索框内容
const Labelvalue = ref(''); //搜索框内容
const searchData = ref([]); //搜索后列表
const value = ref('');
// 图片上传
// const handleAvatarSuccess = (response, uploadFile) => {
//   console.log(response);
//   console.log(uploadFile);
//   form.avatar = response.data.url;
// };
// const uploadError = (error, uploadFile) => {
//   console.log(error);
//   console.log(uploadFile);
//   form.avatar = response.data.url;
// };
// 表单效验
const rules = reactive({
  back: [
    {
      required: true,
      message: '请选择背景颜色',
      trigger: 'change',
    },
  ],
  name: [
    {
      required: true,
      message: '请输入标签名称',
      trigger: 'change',
    },
  ],
  color: [
    {
      required: true,
      message: '请选择字体颜色',
      trigger: 'change',
    },
  ],
});
//分页数据显示
const pageData = computed(() => {
  console.log();
  let a = [];
  for (
    let i = (currentPage.value - 1) * pageSize.value;
    i < currentPage.value * pageSize.value;
    i++
  ) {
    if (searchData.value[i]) {
      a.push(searchData.value[i]);
    }
  }
  console.log(a);
  return a;
});
const copyColor = (color) => {
  navigator.clipboard.writeText(color);
  ElMessage({
    type: 'success',
    message: '复制成功',
  });
}

// 搜索
const searchDepart = () => {
  console.log(value.value);

  searchData.value = LabelList.value.filter(function (item) {
    let date = new Date(item.create_time).getTime();
    if (value.value) {
      let star = new Date(value.value[0]).getTime();
      let end = new Date(value.value[1]).getTime();
      if (date > star && date < end && item.name.indexOf(Labelvalue.value) > -1) {
        return item;
      }
    } else {
      if (item.name.indexOf(Labelvalue.value) > -1) {
        return item;
      }
    }
  });
  listNum.value = searchData.value.length;
};
// 请求列表
const requestList = async () => {
  try {
    const res = await Label();
    console.log('标签列表', res);
    LabelList.value = res.data;
    searchDepart();
    loading.value = false;
    console.log('初次列表', searchData.value);
  } catch (error) {
    console.error(error);
  }
};
requestList();
// 每页显示数量改变
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  console.log(`${val} items per page`);
};
// 页码数改变
const handleCurrentChange = (val) => {
  currentPage.value = val;
  console.log(`current page: ${val}`);
};
// 编辑
const handleEdit = (index, row) => {
  dialogFormVisible.value = true;
  form.id = row.id;
  form.name = row.name;
  form.color = row.color;
  form.back = row.back;
  form.status = row.status;
  console.log(form);
  console.log(index, row);
};
// 删除
const handleDelete = (index, row) => {
  console.log(index, row);
  ElMessageBox.confirm('是否确认删除?', '删除医生', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then((res) => {
      console.log(res);

      deleteLabel({
        id: row.id,
      }).then((result) => {
        console.log(result);
        if (result.code == 0) {
          ElMessage({
            type: 'danger',
            message: result.msg,
          });
        } else if (result.code == 1) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          });
          requestList();
        }
      });
    })
    .catch((res) => {
      console.log(res);
      ElMessage({
        type: 'info',
        message: '取消删除',
      });
    });
};
const deleteBatches = () => {
  let arr = table.value.getSelectionRows();
  if (arr.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请选择需要删除的数据',
    });
    return;
  }

  ElMessageBox.confirm('是否确认删除?', '删除医生', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then((res) => {
      console.log(res);
      let arr = table.value.getSelectionRows();
      let arrs = [];
      console.log(arr);
      // 构造一个 Promise 数组，每个 Promise 表示一条记录的删除操作
      const promises = arr.map((element) => {
        return deleteLabel({ id: element.id });
      });
      // 使用 Promise.all() 处理 Promise 数组，一旦其中有一个Promise被拒绝（即删除失败），就会执行catch()方法，
      // 否则，如果所有的Promise都得到了解决（即删除成功），就会执行then()方法。
      Promise.all(promises)
        .then((results) => {
          console.log(results);
          results.forEach((result) => {
            if (result.code == 0) {
              ElMessage({
                type: 'danger',
                message: result.msg,
              });
            } else if (result.code == 1) {
              arrs.push(result.data);
            }
          });
          if (arrs.length == arr.length) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            });
          } else {
            ElMessage({
              type: 'warning',
              message: '删除失败，请重试',
            });
          }
          requestList();
        })
        .catch((error) => {
          console.log(error);
          ElMessage({
            type: 'warning',
            message: '删除失败，请重试',
          });
        });
    })
    .catch((res) => {
      console.log(res);
      ElMessage({
        type: 'info',
        message: '取消删除',
      });
    });
};
// 新增
const addOffice = () => {
  form.id = '';
  // clearForm();
  dialogFormVisible.value = true;
  ruleFormRef.value.clearValidate();
};
// 清空表单
const clearForm = () => {
  form.back = '';
  form.name = '';
  form.color = '';
  form.status = true;
  console.log(form);
};
// 取消
const cancel = (formEl) => {
  clearForm();
  formEl.resetFields();
  dialogFormVisible.value = false;
};
// 确认新增/编辑科室
const affirm = async (formEl) => {
  console.log(form);
  if (form.status) {
    form.status = 1;
  } else {
    form.status = 2;
  }
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      addLabel(form).then((res) => {
        console.log(res);
        ElMessage({
          type: 'success',
          message: res.msg,
        });
        dialogFormVisible.value = false;
        clearForm();
        formEl.resetFields();
        requestList();
      });
      console.log('submit!');
    } else {
      console.log('error submit!', fields);
    }
  });
};
// 列表状态编辑
const affirmSwitch = (data) => {
  console.log(data);
  if (data.status == 1) {
    data.status = 2;
  } else {
    data.status = 1;
  }

  addLabel(data).then((res) => {
    console.log(res);
    if (res.code == 0) {
      ElMessage({
        type: 'danger',
        message: '状态更改失败',
      });
    } else {
      ElMessage({
        type: 'success',
        message: '状态更改成功',
      });
    }

    requestList();
  });
};
</script>

<style lang="scss" scoped>
.box {
  width: 100%;
  background-color: rgb(255, 255, 255);
  overflow-y: scroll;
}

.left {
  display: flex;
  align-items: center;
}

.header {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.head_word {
  width: 100%;
  padding: 10px 20px;
  border-bottom: 1px solid #e5e5e5;
  margin-bottom: 20px;
  color: #427eff;
}

.window {
  width: 100%;
  // overflow-x: scroll;
  padding: 10px;
  background-color: white;
}

.hint {
  margin-left: 10px;
  color: #a6a6a6;
  font-size: 14px;
}

.head_img {
  width: 40px;
  height: 40px;
  border-radius: 40px;
}

.lable {
  width: 100%;
  line-height: 1;
  border-radius: 50px;
  padding: 10px;
}

.list_word {
  width: 100%;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.inpuut_box {
  width: 800px;
  display: flex;
  flex-wrap: wrap;
}

.box_top {
  width: 400px;
}

.box_bottom {
  width: 800px;
}

.backeds {
  width: 30px;
  height: 30px;
}

//上传
.avatar-uploader {
  border: 1px dashed var(--el-border-color) !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  display: flex;
  align-items: center;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

//上传
.form_word {
  margin-right: 20px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
